package com.james.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.james.mapper.MenuMapper;
import com.james.domain.Menu;
import com.james.service.MenuService;
import org.springframework.util.CollectionUtils;

/**
  * @ClassName: MenuServiceImpl
  * @Author: JamesWang
  * @Date: 2021/4/22 12:26
  * @Description:
  * @Version:1.0
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService{

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 获得菜单树
     * 使用循环方法
     */
    public List<Menu> getMenuTree2() {
        List<Menu> menus = menuMapper.selectList(new LambdaQueryWrapper<Menu>());
        return toTree(menus, 0);
    }

    private List<Menu> toTree(List<Menu> menus, Integer parentId) {
        List<Menu> children = menus.parallelStream().filter(menu -> parentId.equals(menu.getParentId())).collect(Collectors.toList());
        children.forEach(menu -> menu.setChildMenu(toTree(menus,menu.getMenuId())));
        return children;
    }

    /**
     * 获得菜单树
     * 使用递归方法
     */
    @Override
    public List<Menu> getMenuTree() {
        List<Menu> menus = menuMapper.selectList(new LambdaQueryWrapper<Menu>());
        // key为父节点Id value为menuList
        Map<Integer, List<Menu>>  menuMap = menus.stream().collect(Collectors.groupingBy(Menu::getParentId, Collectors.toList()));
        return getTree(menuMap, 0);
    }

    private List<Menu> getTree(Map<Integer, List<Menu>> menuMap, Integer parentId) {
        List<Menu> children = menuMap.get(parentId);
        if (CollectionUtils.isEmpty(children)) {
            return Collections.emptyList();
        }
        for (Menu menu : children) {
            menu.setChildMenu(getTree(menuMap, menu.getMenuId()));
        }
        return children;
    }

}
